package com.example.sevenhomework

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.database.Cursor
import android.media.MediaPlayer
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.core.app.NotificationCompat
import kotlinx.coroutines.channels.Channel
import java.io.IOException

class MusicService : Service() {
    private var notificationManager: NotificationManager? = null
    companion object {
        val Commond = "Operate"
    }
    val Channel_ID = "music channel"
    val Notification_ID = 1
    val TAG = "MusicService"
    val mediaPlayer = MediaPlayer()
    val musicList : MutableList<String> = mutableListOf<String>()
    val musicNameLis : MutableList<String> = mutableListOf<String>()
    var current = 0
    var isPause = false
    var binder = MusicBinder()
    inner class MusicBinder : Binder() {
        val musicName:String
            get() = musicNameLis[current]
        var currentPosition:Int
            get() = mediaPlayer.currentPosition
            set(value) {
                mediaPlayer.seekTo(value)
            }
        val duration : Int
            get() = mediaPlayer.duration
        var size : Int = 0
            get() = musicList.size
        var currentIndex:Int = 0
            get() = current
    }
    override fun onCreate() {
        super.onCreate()
        getMusicList()
        mediaPlayer.setOnPreparedListener{
            it.start()
        }
        mediaPlayer.setOnCompletionListener {
            current ++
            if (current >= musicList.size) {
                current = 0
            }
            play()
        }
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this, 1, intent,
            PendingIntent.FLAG_IMMUTABLE // 添加FLAG_IMMUTABLE标志
        )
        // 初始化通知管理器
        notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val builder: Notification.Builder
        // 创建通知渠道（Android 8.0及以上需要）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(Channel_ID, "Music Channel", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager?.createNotificationChannel(notificationChannel)
            builder = Notification.Builder(this, Channel_ID)
        }else {
            builder = Notification.Builder(this)
        }
        val notification:Notification = builder.setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("Music Service")
            .setContentText("Running")
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()

        notificationManager?.notify(Notification_ID, notification)
    }
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val operate = intent?.getIntExtra(Commond, 1) ?:1
        when (operate) {
            1 -> play()
            2 -> pause()
            3 -> stop()
            4 -> next()
            5 -> prev()
        }
        return super.onStartCommand(intent, flags, startId)
    }
    // 新增方法，用于更新通知
    fun play(){
        if (musicList.size == 0) {
            return
        }
        val path: String = musicList[current]
        mediaPlayer.reset()
        try {
            mediaPlayer.setDataSource(path)
            mediaPlayer.prepareAsync()
            mediaPlayer.setOnPreparedListener {
                it.start()
                updateNotification(musicNameLis[current])
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    fun pause() {
        if (isPause) {
            mediaPlayer.start()
            isPause = false
        } else {
            mediaPlayer.pause()
            isPause = true
        }
    }
    fun stop() {
        mediaPlayer.stop()
    }
    fun next() {
        current ++
        if (current >= musicList.size) {
            current = 0
        }
        play()
    }
    fun prev() {
        current --
        if (current < 0) {
            current = musicList.size - 1
        }
        play()
    }
    override fun onBind(intent: Intent): IBinder {
        return binder
    }
    @SuppressLint("Range")
    private fun getMusicList() {
        val cursor : Cursor? = contentResolver.query(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null)
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val musicPath : String = cursor.getString(cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DATA))
                val musicName : String = cursor.getString(cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DISPLAY_NAME))
                musicList.add(musicPath)
                musicNameLis.add(musicName)
                Log.d(TAG, "getMusicList: $musicPath name:$musicName")
            }
            cursor.close()
        }
    }
    // 新增方法，用于更新通知
    private fun updateNotification(musicName: String) {
        val notificationBuilder: Notification.Builder
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationBuilder = Notification.Builder(this, Channel_ID)
        } else {
            notificationBuilder = Notification.Builder(this)
        }
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this, 1, intent,
            PendingIntent.FLAG_IMMUTABLE // 添加FLAG_IMMUTABLE标志
        )
        val notification: Notification = notificationBuilder.setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("Now Playing")
            .setContentText(musicName)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()
        notificationManager?.notify(Notification_ID, notification)
    }
}